#!usr/bin/env node

const http = require('http'),
      fs = require('fs'),
      qs = require('querystring'),
      log = require('util').debuglog('UPLOAD-FILE'),
      path = require('path');

let errorPage = `
<!DOCTYPE html>
<html>
    <head>
      <meta charset="UTF-8">
      <title>Error</title>
    </head>
    <body>
      <h1>Sorry! There is  nothing!</h1>
      <a href="/">back to upload file</a>
    </body>
</html>`;


http.createServer((req,res)=>{

  printRequest(req);

  if(req.method === 'GET' && req.url === '/'){
    show(res,uploadPage());
    return;
  }

  if(req.method === 'GET' && req.url.split('/')[1] === 'images'){
    sendPic(req,res);
    return;
  }

  if(req.method === 'POST' && req.url === '/upload'){
    req.setEncoding('binary');
    let file;

    req.on('data',(data) => file += data);
    req.on('end',()=>{
      if(writePic(file)){
        show(res,uploadPage());
      }else{
        show(res,errorPage);
      }
    });

    return;
  }

  show(res,errorPage);
}).listen(8080)
                 
function show(res,page){
  res.statusCode = 404;
  res.setHeader('Content-Length',page.length);
  res.setHeader('Content-Type','text/html');

  res.end(page);
}

function writePic(file){
  let data = file.split('\r\n');
  let fileName = qs.parse(data[1].split(';').trim())['filename'],
      start = data[0].length + data[1].length + data[2].length + data[3].length + 8,
      end = file.indexOf('-----------WebKitFormBoundary',start),
      buf = file.slice(start,end);

  fileName = fileName.slice(1,fileName.length -1);

  if(fileName === '') return false;

  fileName = path.join(__dirname,'images',fileName);
  fs.writeFileSync(fileName,buf,{'encoding':'binary'});

  return true;
      
}

function sendPic(req,res){
  let info = req.url.split('/'),
      pic = path.join(__dirname,req.url),
      ext = info[2].split('.')[1];

  if(info.length !== 3 || !fs.existsSync(pic)){
    show(res,errorPage);
    return;
  }

  res.statusCode = 200;
  res.setHeader('Content-Type','image/' + ext);
  res.setHeader('Content-Length',fs.statSync(pic).size);
  res.end(fs.readFileSync(pic));
}

function printRequest(req){
  log(`${req.method} ${req.url} HTTP/${req.httpVersion}`);
  log(req.headers);
  log('');
}

